use std::{
    net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener},
    os::windows::io::AsRawSocket,
};
use windows_sys::Win32::{
    Foundation::INVALID_HANDLE_VALUE,
    System::{
        SystemInformation::{GetSystemInfo, SYSTEM_INFO},
        IO::{CreateIoCompletionPort, GetQueuedCompletionStatus},
    },
};

pub struct Server
{
    port: u16,
    iocp: isize,
    listener: TcpListener,
    //buf_size: u32,
    //clients: u32,
    //messages: [usize; 1000],
}
impl Server
{
    fn new(port: u16) -> Result<Self, String>
    {
        let bind_result = TcpListener::bind(SocketAddr::V4(SocketAddrV4::new(
            Ipv4Addr::new(0, 0, 0, 0),
            port,
        )));
        let listener;
        match bind_result
        {
            Ok(l) =>
            {
                listener = l;
            }
            Err(e) =>
            {
                return Err(format!("绑定端口出错 {:?}", e));
            }
        }
        let iocp = unsafe { CreateIoCompletionPort(INVALID_HANDLE_VALUE, 0, 0, 0) };
        let s = Server {
            port: port,
            iocp: iocp,
            listener: listener,
        };

        let at = std::thread::spawn(move || s.accept_thread());

        let mut sysInfo: SYSTEM_INFO = unsafe { std::mem::zeroed::<SYSTEM_INFO>() };
        unsafe { GetSystemInfo(&mut sysInfo as *mut SYSTEM_INFO) };
        let wt_num = sysInfo.dwNumberOfProcessors * 2;
        for i in 0..wt_num
        {
            std::thread::spawn(move || s.work_thread(i));
        }
        Ok(s)
    }

    fn accept_thread(&self)
    {
        loop
        {
            let accept_result = self.listener.accept();
            match accept_result
            {
                Ok(_) => todo!(),
                Err(_) => todo!(),
            }
        }
    }
    fn work_thread(&self, i: u32)
    {
        println!("线程号={}", i);
        unsafe //...
        {
            //let r = GetQueuedCompletionStatus( self.iocp, &dwTrans, (LPDWORD)&pPerHandle, (LPOVERLAPPED*)&pPerIo, WSA_INFINITE );
        };
    }
}
